package com.example.passport.controller;


import com.alibaba.fastjson.JSONObject;
import com.example.common.dto.JsonResult;
import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.front.entity.Equipment;
import com.example.interceptor.UserContext;
import com.example.passport.dto.UserDto;
import com.example.passport.dto.WxUserDto;
import com.example.passport.entity.Tenant;
import com.example.passport.entity.User;
import com.example.passport.entity.WxToken;
import com.example.passport.entity.WxUser;
import com.example.passport.mapper.TenantMapper;
import com.example.passport.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@Api(tags = "企业微")
@RestController
@CrossOrigin
@RequestMapping("/passport/wx")
public class WxController {

    @Value("${com.shangqi.corpid}")
    private String corpid;

    @Value("${com.shangqi.corpsecret}")
    private String corpsecret;

    @Resource
    TenantMapper tenantMapper;
    @Resource
    WxUserService wxUserService;

    @GetMapping("/synUser")
    @ApiOperation("同步当前工厂的微信人员")
    public JsonResult<String> synUser() {

        User user = UserContext.getUser();
        Long tenantId = user.getTenantId();
        WxToken wxToken = getWxToken();

        Tenant bytenantId = tenantMapper.findBytenantId(tenantId);

        if (wxToken == null) {
            throw new BusinessException("同步失败");
        } else if (wxToken.getErrcode() != 0) {
            throw new BusinessException(wxToken.getErrcode() + " : " + wxToken.getErrmsg());
        } else {
            WxUser wxUser = getWxUser(wxToken.getAccess_token(), bytenantId.getWxDep());
            System.out.println(wxUser);
            if (wxUser != null){
                List<WxUserDto> userlist = wxUser.getUserlist();
                for (WxUserDto wxUserDto : userlist) {
                    wxUserDto.setTenantId(tenantId);
                    int i = wxUserService.insertWxUser(wxUserDto);
                }
            }else if (wxUser.getErrcode() != 0){
                throw new BusinessException(wxUser.getErrcode() + " : " + wxUser.getErrmsg());
            }
            return new JsonResult<>("同步成功");
        }
    }


    @GetMapping("/list")
    @ApiOperation("获取用户信息")
    public JsonResult<ListDto<WxUserDto>> list(@Valid WxUserDto condition, Pagination pagination) {
        condition.setTenantId(UserContext.getUser().getTenantId());
        return new JsonResult<>(wxUserService.list(condition, pagination));
    }


    public WxToken getWxToken() {

        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;

        String res = getUrl(url);

        if (res != null){
            WxToken wxToken = JSONObject.parseObject(res, WxToken.class);
            return wxToken;
        }
        return null;
    }

    public WxUser getWxUser(String token , int tenantId){
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();


        //https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?
        // access_token=IrS5bVfPMK6cflC9h7WoT3VOAlA6cssvK0FdhQh5Ie4VY12sFiPbOxttuJr9VPwr5U9LD6kDVB9K_ZzJtAbCzIwAEa2jlCeZCQp6nrQB4G7v19VlS3otC68ckHqLdq6JUSpZZr3zF3FkTGo59n2hcGl0w-CAjFLSMadfXrTaLlVrXuY63tz6I0YfVt179EsqOI3s5HW6uL9Mvv03l-6vVQ
        // &department_id=4

//        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" + token + "&department_id=" + tenantId;
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + token + "&department_id=" + tenantId;

        String res = getUrl(url);

        if (res != null){
            WxUser wxUser = JSONObject.parseObject(res, WxUser.class);
            return wxUser;
        }

        return null;
    }

    //Get请求
    public String getUrl(String url){
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建HttpGet对象
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            // 3. 执行GET请求
            response = httpClient.execute(httpGet);
//            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//
//            }
            String res = EntityUtils.toString(response.getEntity());
            return res;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 6. 释放资源
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
